import Vue from "vue";
import NProgress from "nprogress";
import "nprogress/nprogress.css";
import store from "@/store";
import VueRouter from "vue-router";

let routes = [];

function rename(str) {
  return str.charAt(0) + str.slice(1);
}

const requireModules = require.context("./modules", false, /\.js$/);

let modules = {};

requireModules.keys().forEach((fileName) => {
  let config = requireModules(fileName);
  let apiName = rename(fileName.replace(/^\.\//, "").replace(/\.\w+$/, ""));
  modules[apiName] = config.default;
});

Object.keys(modules).forEach((name) => {
  if (name !== "index") {
    routes.push(...modules[name]);
  }
});

Vue.use(VueRouter);

const router = new VueRouter({
  scrollBehavior: () => ({ y: 0 }),
  routes
});

const whiteList = ["/login", "/404"];

router.beforeEach((to, form, next) => {
  NProgress.start();
  const token = store.getters.token;
  if (token) {
    if (to.path === "/login") {
      next({ path: "/" });
    } else {
      next();
    }
  } else {
    if (whiteList.includes(to.path)) {
      next();
    } else {
      next(`/login`);
    }
  }
  NProgress.done();
});
export default router;
